package com.duobaoyu.dby.supply.biz.service.config.impl;

import com.duobaoyu.dby.channel.adapter.enums.ChannelCodeEnum;
import com.duobaoyu.dby.common.core.constant.CommonConstants;
import com.duobaoyu.dby.supply.biz.converter.BalanceWarnConverter;
import com.duobaoyu.dby.supply.biz.service.config.BalanceWarnService;
import com.duobaoyu.dby.supply.common.biz.bo.config.BalanceWarnBO;
import com.duobaoyu.dby.supply.common.biz.dto.config.BalanceWarnBatchDTO;
import com.duobaoyu.dby.supply.common.biz.dto.config.BalanceWarnDTO;
import com.duobaoyu.dby.supply.core.dinger.util.DingDingUtils;
import com.duobaoyu.dby.supply.db.entity.config.BalanceWarn;
import com.duobaoyu.dby.supply.db.repository.config.BalanceWarnRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 001
 * @Date 2022/6/7 10:44
 * @Version 1.0
 * @Description
 */
@Service("balanceWarnService")
@Slf4j
@RequiredArgsConstructor
public class BalanceWarnServiceImpl implements BalanceWarnService {

	private final BalanceWarnRepository balanceWarnRepository;
	private final BalanceWarnConverter balanceWarnConverter;


	@Override
	public Boolean modify(BalanceWarnDTO balance) {
		BalanceWarn balanceWarn = balanceWarnConverter.toBalanceWarn(balance);
		// 前端传递的单位是元，数据库统一存储为分
		balanceWarn.setWarnAmount(balance.getWarnAmount().multiply(new BigDecimal(CommonConstants.HUNDRED)));
		boolean result = balanceWarnRepository.updateById(balanceWarn);
		if(result) {
			//  发送钉钉消息
			DingDingUtils.sendMarkdownMsg(
					String.format("修改余额预警金额:%s元\n接收短信手机号-%s",
							balanceWarn.getWarnAmount().divide(BigDecimal.valueOf(CommonConstants.HUNDRED), CommonConstants.TWO, RoundingMode.HALF_UP),
							balanceWarn.getPhoneNumber()));
		}
		return result;
	}

	@Override
	public Boolean batchSave(BalanceWarnBatchDTO balanceWarnBatch) {
		List<Long> id = balanceWarnRepository.list().stream().map(BalanceWarn::getId).collect(Collectors.toList());
		return balanceWarnRepository.lambdaUpdate().set(BalanceWarn::getPhoneNumber, balanceWarnBatch.getPhoneNumber()).in(BalanceWarn::getId, id).update();
	}

	@Override
	public BalanceWarnBO queryBalanceWarn() {
		List<BalanceWarn> balanceWarn = balanceWarnRepository.list();
		return BalanceWarnBO.builder().phoneNumber(balanceWarn.stream().findFirst().map(BalanceWarn::getPhoneNumber).orElse(null))
				.data(balanceWarn.stream().map(item -> BalanceWarnBO.BalanceWarnInfo.builder()
						.id(item.getId()).channelCode(item.getChannelCode()).enable(item.getEnable())
						.channelName(ChannelCodeEnum.getChannelCodeEnumByCode(item.getChannelCode()).getDescribe())
						.warnAmount(item.getWarnAmount().divide(BigDecimal.valueOf(CommonConstants.HUNDRED), CommonConstants.TWO, RoundingMode.HALF_UP))
						.build()).collect(Collectors.toList())).build();
	}
}
